# -*- coding: utf-8 -*-

import random
from netaddr import IPAddress, IPNetwork
from misc.exec_cmd import exec_cmd, safe_exec_cmd
from log.logger import logger


def random_mac():
    mac = None
    while True:
        MAC = [0x00, 0x16, 0x3e,
            random.randint(0x00, 0x7f),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff)
        ]
        mac = ':'.join(map(lambda x: "%02x" % x, MAC))

    return mac

def is_valid_address(address, version=4):
    if version == 6 and address.upper().startswith('FE80'):
        return False

    try:
        address = IPAddress(address, flags=1)
        if address.version != version:
            return False
        else:
            return True
    except Exception:
        return False

def get_valid_address(address):
    try:
        return IPAddress(address, flags=1)
    except:
        return None

def is_valid_network(network, version=4):
    try:
        network = IPNetwork(network, flags=1)
        if network.version != version:
            return False
        else:
            if network.prefixlen in [31, 32, 127, 128]:
                return False
            else:
                return True
    except:
        return False

def get_valid_network(network):
    try:
        return IPNetwork(network, flags=1)
    except:
        return None

def getIfIPs():
    import socket
    import struct
    import array
    import fcntl
    max_possible = 128  # arbitrary. raise if needed.
    bytes = max_possible * 32
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    names = array.array('B', b'\0' * bytes)
    result = fcntl.ioctl(
        s.fileno(),
        0x8912,
        struct.pack('iL', bytes, names.buffer_info()[0])
    )
    outbytes = struct.unpack('iL', result)[0]
    namestr = names.tostring()
    interface_ip = {}
    for i in range(0, outbytes, 40):
        name = namestr[i:i+16].split(b'\0', 1)[0].decode('utf-8')
        ip = socket.inet_ntoa(namestr[i + 20:i + 24])
        if name in interface_ip:
            interface_ip[name].append(ip)
        else:
            interface_ip[name] = [ip]
    return interface_ip
